<?php
/**
 * Created by PhpStorm.
 * User: kun
 * Date: 26/6/19
 * Time: 18:20
 */

namespace app\api\controller\v1;


use app\api\controller\Common;
use app\common\lib\exception\ApiException;
use think\Log;

class Index extends Common
{
    /**
     * 获取首页列表
     * 1.头图 4-6
     * 2.推存位列表 默认40条
     * @return array
     */
    public function index()
    {
        $heads = model('News')->getIndexHeadNormalNews();
        $heads = $this->getDealNews($heads);
        $positions = model('News')->getPositionNormalNews();
        $positions = $this->getDealNews($positions);
        $result = [
            'heads' => $heads,
            'positions' => $positions,
        ];
        return show(config('code.success'), 'ok', $result, 200);
    }

    /**
     * 客户端初始化接口
     * 1、检测APP是否需要升级
     */
    public function init()
    {
        // app_type 去ent_version 查询
        try {
            $versioncate = model('Versioncate')->get(['name' => $this->headers['apptype']]);
        } catch (\Exception $e) {
            return new ApiException('客户端初始化接-error', 400);
        }
        $version = model('Version')->getLastNormalVersionByAppType($versioncate['id']);
        try {
            $version = model('Version')->getLastNormalVersionByAppType($versioncate['id']);
        } catch (\Exception $e) {
            return new ApiException('客户端初始化接-error', 400);
        }
        if (empty($version)) {
            return new ApiException('客户端初始化接-error', 404);
        }
        if ($version->version > $this->headers['version']) {
            $version->is_update = $version->is_force == 1 ? 2 : 1;
        } else {
            $version->is_update = 0;  //0 不更新
        }

        // 记录用户的基本信息 用于统计
        $actives = [
            'version' => $this->headers['version'],
            'app_type' => $this->headers['apptype'],
            'did' => $this->headers['did'],
            'model' => $this->headers['model']
        ];

        try {
            model('AppActive')->add($actives);
        } catch (\Exception $e) {
            Log::write($e->getMessage());
//            return new ApiException($e->getMessage(), 400);
        }


        return show(config('code.success'), 'ok', $version, 200);

    }

}